<template>
  <div class="admin-sessions">
    <div class="header">
      <h2>在线会话管理</h2>
      <div class="actions">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索用户名"
          style="width: 300px"
          @search="loadSessions"
        />
        <a-button @click="loadSessions" :loading="loading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </div>
    </div>

    <a-table
      :columns="columns"
      :data-source="sessions"
      :loading="loading"
      row-key="token"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'username'">
          <a-tag color="blue">{{ record.username || '未知用户' }}</a-tag>
        </template>
        
        <template v-if="column.key === 'roles'">
          <a-tag
            v-for="role in (record.roles || '').split(',')"
            :key="role"
            :color="getRoleColor(role)"
          >
            {{ role }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'ttlSeconds'">
          <span v-if="record.ttlSeconds > 0">
            {{ formatTTL(record.ttlSeconds) }}
          </span>
          <span v-else class="expired">已过期</span>
        </template>
        
        <template v-if="column.key === 'actions'">
          <a-popconfirm
            title="确定要踢出此用户吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="kickoutUser(record)"
          >
            <a-button type="link" danger size="small">
              踢出
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <div class="footer">
      <a-statistic
        title="在线用户数"
        :value="sessions.length"
        style="margin-right: 32px"
      />
      <a-statistic
        title="活跃会话数"
        :value="activeSessions"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { listOnlineSessions, kickoutSession } from '@/api/admin'

interface OnlineSession {
  token: string
  userId: number
  username: string
  roles: string
  ttlSeconds: number
}

const loading = ref(false)
const searchKeyword = ref('')
const sessions = ref<OnlineSession[]>([])

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 150,
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 100,
  },
  {
    title: '角色',
    dataIndex: 'roles',
    key: 'roles',
    width: 200,
  },
  {
    title: '剩余时间',
    dataIndex: 'ttlSeconds',
    key: 'ttlSeconds',
    width: 150,
  },
  {
    title: 'Token',
    dataIndex: 'token',
    key: 'token',
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    fixed: 'right',
  },
]

const activeSessions = computed(() => {
  return sessions.value.filter(s => s.ttlSeconds > 0).length
})

const loadSessions = async () => {
  try {
    loading.value = true
    const response = await listOnlineSessions(searchKeyword.value)
    if (response.success) {
      sessions.value = response.data || []
    } else {
      message.error(response.message || '获取会话列表失败')
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    message.error('获取会话列表失败')
  } finally {
    loading.value = false
  }
}

const kickoutUser = async (session: OnlineSession) => {
  try {
    const response = await kickoutSession(session.token)
    if (response.success) {
      message.success('用户已被踢出')
      await loadSessions()
    } else {
      message.error(response.message || '踢出用户失败')
    }
  } catch (error) {
    console.error('踢出用户失败:', error)
    message.error('踢出用户失败')
  }
}

const getRoleColor = (role: string) => {
  const colorMap: Record<string, string> = {
    'ADMIN': 'red',
    'EDITOR': 'orange',
    'USER': 'green',
  }
  return colorMap[role] || 'default'
}

const formatTTL = (seconds: number) => {
  if (seconds <= 0) return '已过期'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟${secs}秒`
  } else {
    return `${secs}秒`
  }
}

onMounted(() => {
  loadSessions()
})
</script>

<style scoped>
.admin-sessions {
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
}

.actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.expired {
  color: #ff4d4f;
  font-weight: 500;
}

.footer {
  margin-top: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
  display: flex;
  align-items: center;
}
</style>